<?php
require_once "../lib/common.php";
$response = array();

if ( ! empty($_POST) ) {
    if (isset($_POST['text'])) {
        $_POST['text'] = htmlentities($_POST['text']);
    }
    if ( isset($_POST['add_review'])) {
        if (Login::getLoggedIn() == null) {
            error_die("you are not logged-in");
        }
        if ( ! isset($_POST['book_id']) ) {
            error_die("invalid input");
        }
        $cond = array( 'id' => $_POST['book_id']);
        if ( count(Book::find($cond)) != 1 ) {
            error_die("invalid book");
        }
        unset($cond);

        $params = $_POST;
        $params['user_id'] = Login::getLoggedIn()->id;

        $review = new Review();
        $ret = $review->update_attributes_filter($params,$review->attributes());
        if ($ret == false) {
            $err_msgs = $review->errors->full_messages();
            error_die($err_msgs[0]);
        }
    } else {
        $userLoggedIn = Login::getLoggedIn();
        if ($userLoggedIn == null) {
            error_die("access denied");
        }
        if ($userLoggedIn->admin != 1 && $userLoggedIn->employee != 1) {
            error_die("access denied");
        }
        if ( isset($_POST['delete']) ) {
            $review = Review::find($_POST['id']);
            $review->delete();
        }
    }
} else {
    $faux = new Review();
    $response['attributes'] = array_keys(
        $faux->attributes_but(array("book_id","user_id")));
    array_push($response['attributes'],"book");
    array_push($response['attributes'],"user");
    unset($faux);
    if (isset($_GET['book'])) {
        $options = array(
            'conditions' => array('book_id'=>(int)$_GET['book']),
            'order' => 'created_at'
        );
        $reviews = Review::all($options);
    } else {
        $options = array('order' => 'created_at');
        $reviews = Review::all($options);
    }
    $review_collection = array();
    foreach ($reviews as $review) {
        $attrs = $review->attributes_but(array("created_at","book_id","user_id"));
        $attrs['created_at'] = $review->created_at->format('Y-m-d H:i');
        $attrs['book'] = $review->book->attributes_but(
            array("description","on_stock","category_id","created_at","updated_at"));
        if ($review->user) {
            $attrs['user'] = $review->user->attributes_but(array("email"));
        } else {
            $attrs['user'] = array("id" => 0,"name"=>"&lt;user deleted&gt;");
        }
        array_push($review_collection,$attrs);
    }
    $response['collection'] = $review_collection;
}

if (!empty($response)) {
    echo json_encode($response);
}
?>
